//
//  XXData.swift
//  XXSwiftDemo
//
//  Created by admin on 2022/3/25.
//

import Foundation
import UIKit

extension Data {
    
    /// Data转String
    func string() -> String? {
        return String.init(data: self, encoding: String.Encoding.utf8)
    }
    
    /// 从资源里获取data数据
    static func dataFor(resource: String, ofType: String) -> Data? {
        let path = Bundle.main.path(forResource: resource, ofType: ofType);
        if (path == nil) {
            return nil;
        }
        return try? Data.init(contentsOf: URL.init(string: path!)!);
    }
    
    static func dataFor(resource: String) -> Data? {
        return Data.dataFor(resource: resource, ofType: "");
    }
    
    // 根据压缩质量压缩图片成Data数据
    static func frome(image: UIImage, _ quality: CGFloat = 1.0) -> Data? {
        var data = image.jpegData(compressionQuality: quality)
        if (data == nil) {
            data = image.pngData()
        }
        return data
    }
    
    // 压缩图片在设定的大小内
    static func compressed(image: UIImage, _ limitSize: Int) -> Data? {
        let imagePixel = image.cgImage!.width * image.cgImage!.height;  // 图片像素
        let imageSize = imagePixel * (image.cgImage?.bitsPerPixel)! / (8 * 1024);
        if imageSize > limitSize {
            let compressedParam = CGFloat(limitSize) / CGFloat(imageSize)
            return image.jpegData(compressionQuality: compressedParam)
        }
        return image.pngData()
    }
}
